﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ChatServer.model
{
    public class Chat : dbconn.DBConnector
    {
        //parsed message from xml
        private String _message;
        //roomName variable for room message belongs in
        private String _roomName;
        //senders username
        private String _senderUserName;
        //datetime value of message
        private DateTime _timeStamp;

        //public getters and setters
        public string RoomName
        {
            get { return _roomName; }
            
        }

        public string Message
        {
            get { return _message; }
            
        }

        public string SenderUserName
        {
            get { return _senderUserName; }
            
        }

        public string TimeStamp
        {
            get { return _message; }
            
        }

        //method used to parse xml messages
        public void parseXml(string rawXml)
        {
            //list used for storing parsed strings
            List<string> tempList = null;

            //use of Linq to XML to parse message
            var chatMessage = XDocument.Parse(rawXml);

            //query document using linq
            var data = from xmlElement in chatMessage.Descendants("type")
                       select new
                       {
                           //assign values
                           roomName = xmlElement.Element("roomname").Value,
                           message = xmlElement.Element("msg").Value,
                           senderUserName = xmlElement.Element("sender").Value,
                           timeStamp = xmlElement.Element("timestamp").Value
                       };

            //loop through results
            foreach (var p in data)
            {
                //add each value to tempList
                tempList.Add(p.ToString());
            }

            //assing private variables
            _roomName = tempList[0];
            _message = tempList[1];
            _senderUserName = tempList[2];
            _timeStamp = DateTime.Parse(tempList[3]);
        }

        //method to create and convert xml message to byte array for sending
        public byte[] chatToByteArray(XmlDocument doc)
        {
            //write xml document to memory stream and convert it to byte array to send
            MemoryStream ms = new MemoryStream();
            doc.Save(ms);
            byte[] bytes = ms.ToArray();

            //return array
            return bytes;
        }

        //method will be used to create Room.xml to send to all users via userSockets
        public XmlDocument createRoomMessage(Room room, List<User> activeUserList)
        {
            //variable for storing correct roomName and user information
            string roomName = room.RoomName;

            //create roomXml to send to user through Usersocket
            //build nodes by xml
            //creating xml form and adding name of the room
            // each user of the room and user ip
            MemoryStream ms = new MemoryStream();
            XmlTextWriter _xWrite = new XmlTextWriter(ms, new UTF8Encoding());
            _xWrite.Formatting = Formatting.Indented;

            //Create the xml of a list of users for this room
            
            _xWrite.WriteStartDocument();
            _xWrite.WriteStartElement("type");
            _xWrite.WriteAttributeString("name", "chat");
            _xWrite.WriteElementString("roomname", roomName);
            _xWrite.WriteStartElement("users");
            foreach (User Usr in activeUserList)
            {
                _xWrite.WriteStartElement("user");
                _xWrite.WriteElementString("username", Usr.UserName);
                _xWrite.WriteElementString("userip", Usr.UserSocket.UserUserSocket.RemoteEndPoint.ToString());
                _xWrite.WriteEndElement();//end "user"

            }
            _xWrite.WriteEndElement();//end "users"
            _xWrite.WriteEndElement();//end "type"
            _xWrite.WriteEndDocument();//end "Userlist.xml"

            //create xml document by loading created xml into it
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(_xWrite.ToString());

            //close connections
            _xWrite.Close();

            return doc;
        }

        //method will be used to create Chat.xml for messages
        public XmlDocument createChatMessage()
        {
            //create chatXml to send to user through Usersocket
            //build nodes by xml
            //creating xml form and adding name of the room
            // each user of the room and user ip
            XmlWriter _xWrite = null;
            //Settings for the XML writer
            XmlWriterSettings _xSettings = new XmlWriterSettings();
            _xSettings.Indent = true;
            _xSettings.IndentChars = ("/t");

            //Create the xml of a list of users for this room
            _xWrite = XmlWriter.Create("chat.xml", _xSettings);
            _xWrite.WriteStartDocument();
            _xWrite.WriteStartElement("type");
            _xWrite.WriteAttributeString("name", "chat");
            _xWrite.WriteElementString("sender", this.SenderUserName);
            _xWrite.WriteElementString("timestamp", this.TimeStamp.ToString());
            _xWrite.WriteElementString("msg", this.Message);
            _xWrite.WriteElementString("roomname", this.RoomName);
            _xWrite.WriteEndElement();//end "type"
            _xWrite.WriteEndDocument();//end "chat.xml"

            //create xml document by loading created xml into it
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(_xWrite.ToString());

            //close connections
            _xWrite.Close();

            return doc;
        }
    


    }
}
